package com.tacuati.content;

import java.util.ArrayList;

import javax.swing.ImageIcon;

import com.tacuati.ui.ContentTreeNode;
import com.tacuati.ui.Icons;

public class Collection implements Comparable<Collection>, ContentTreeNode {
	ImageIcon collectionIcon = new ImageIcon("collection.png");
	
	private String name;
	private String encoding;
	private String lastAccess;

	private ArrayList<Item> items;

	public Collection(String jsonString) {
		this.name = jsonString.substring(0, jsonString.lastIndexOf('@'));
		this.encoding = jsonString.substring(jsonString.lastIndexOf('@') + 1);
		items = new ArrayList<Item>();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public ArrayList<Item> getItems() {
		return items;
	}

	public void setBooks(ArrayList<Item> items) {
		this.items = items;
	}

	public String getEncoding() {
		return encoding;
	}

	public void setEncoding(String encoding) {
		this.encoding = encoding;
	}

	public void setItems(ArrayList<Item> items) {
		this.items = items;
	}

	public String getLastAccess() {
		return lastAccess;
	}

	public void setLastAccess(String lastAccess) {
		this.lastAccess = lastAccess;
	}

	public String toJson() {
		String json = "\"";
		json += name + "@" + encoding + "\":{";
		json += "\"items\":[";
		int i = 0;
		for (Item item : items) {
			if (i > 0) {
				json += ",";
			}
			json += item.toJson();
			i++;
		}
		json += "]";
		json += ",\"lastAccess\": " + lastAccess;
		json += "}";
		return json;
	}

	@Override
	public int compareTo(Collection c) {
		return this.getName().compareTo(c.getName());
	}

	@Override
	public ContentTreeNode getChild(int index) {
		return items.get(index);
	}

	@Override
	public int getChildCount() {
		return items.size();
	}

	@Override
	public int getIndexOfChild(ContentTreeNode child) {
		return items.indexOf(child);
	}

	@Override
	public String getNodeName() {
		return getName();
	}

	@Override
	public void setNodeName(String name) {
		setName(name);
	}
	
	@Override
	public void addChild(int index, ContentTreeNode o) {
		if (items.contains(o)){
			items.add(index, ((Item) o).copy());
		} else {
			items.add(index, (Item) o);			
		}
	}

	@Override
	public void removeChild(int index) {
		items.remove(index);
	}
	
	@Override
	public boolean isEditable() {
		return true;
	}

	@Override
	public ImageIcon getIcon() {
		return Icons.collectionIcon;
	}

	@Override
	public String getNodeRenderer() {
		return getNodeName() + " (" + items.size() + ")";
	}
}
